package com.mars.pay.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mars.pay.config.WechatMiniAppConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 微信小程序服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WechatMiniAppService {

    private final WechatMiniAppConfig wechatMiniAppConfig;
    
    /**
     * 获取微信小程序OpenID
     *
     * @param code 微信临时登录凭证
     * @return OpenID
     */
    public String getOpenId(String code) {
        // 构建请求参数
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session");
        url.append("?appid=").append(wechatMiniAppConfig.getAppId());
        url.append("&secret=").append(wechatMiniAppConfig.getAppSecret());
        url.append("&js_code=").append(code);
        url.append("&grant_type=authorization_code");
        
        // 发送请求
        String response = HttpUtil.get(url.toString());
        log.info("获取微信小程序OpenID响应: {}", response);
        
        // 解析响应
        JSONObject json = JSON.parseObject(response);
        
        // 检查是否有错误
        if (json.containsKey("errcode") && json.getIntValue("errcode") != 0) {
            log.error("获取微信小程序OpenID失败: {}", json.getString("errmsg"));
            throw new RuntimeException("获取OpenID失败：" + json.getString("errmsg"));
        }
        
        return json.getString("openid");
    }
} 